package cn.bearspark.framework.redis.starter.buffer.list;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * Redis 用于分页查询的缓存器的缓存器的抽象父类
 * <p>
 * 注：该缓存器会返回一个 List 的结果
 *
 * @author f
 */
public abstract class RedisPageListBuffer extends RedisBaseListBuffer<Long> {

    private final RedisPageListMapper redisPageListMapper;

    private final RedisPageListBufKeyBuilder redisPageListBufKeyBuilder;

    public RedisPageListBuffer(RedisTemplate<String, Object> redisTemplate,
                               RedisPageListMapper redisPageListMapper,
                               RedisPageListBufKeyBuilder redisPageListBufKeyBuilder) {
        super(redisTemplate);
        this.redisPageListMapper = redisPageListMapper;
        this.redisPageListBufKeyBuilder = redisPageListBufKeyBuilder;
    }

    /**
     * 分页查询 id 集合
     *
     * @param id       待查询的 id
     * @param pageNum  页数
     * @param pageSize 元素数
     * @return id 集合
     */
    public List<Long> page(long id, int pageNum, int pageSize) {
        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize - 1;
        return super.range(redisPageListBufKeyBuilder.buildPageListBufKey(id),
                start, end, () -> redisPageListMapper.listPageId(id, start, pageSize));
    }

    /**
     * 清理缓存
     *
     * @param id 缓存的 id
     */
    public void clean(long id) {
        super.clean(redisPageListBufKeyBuilder.buildPageListBufKey(id));
    }
}
